package com.gedmanager.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class BackupDataSource {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.BACKUP_ID,
			MySQLiteHelper.BACKUP_DATE};

	public BackupDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Backup createBackup( long date) {
		ContentValues values = new ContentValues();

		values.put(MySQLiteHelper.BACKUP_DATE, date);

		long insertId = database.insert(MySQLiteHelper.TABLE_BACKUP, null,
				values);
		Cursor cursor = database.query(MySQLiteHelper.TABLE_BACKUP,
				allColumns, MySQLiteHelper.BACKUP_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		Backup newBackup = cursorToBackup(cursor);
		cursor.close();
		return newBackup;
	}

	public void deleteBackup(long id) {    
		System.out.println("Backup deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_BACKUP, MySQLiteHelper.BACKUP_ID
				+ " = " + id, null);
	}

	public List<Backup> getAllBackups() {
		List<Backup> backups = new ArrayList<Backup>();

		Cursor cursor = database.query(MySQLiteHelper.TABLE_BACKUP,
				allColumns, null, null, null, null, MySQLiteHelper.BACKUP_DATE+" DESC");

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Backup backup = cursorToBackup(cursor);
			backups.add(backup);
			cursor.moveToNext();
		}
		// make sure to close the cursor
		cursor.close();
		return backups;
	}



	private Backup cursorToBackup(Cursor cursor) {
		Backup backup = new Backup();
		backup.setId(cursor.getLong(0));
		backup.setDate(cursor.getLong(1));

		return backup;
	}
} 